# Make partisan voteshare table - does VBM advantage one party in voteshare?
# Note: this is preliminary analysis. we include only the states for which
#       we have 2020 returns (UT, NV, MT, VT).
# By Dom Valentino and Chris Kenny
# libs --------------------------------------------------------------------
library(tidyverse) # select(), mutate(), pivot_longer()
library(lfe) # felm()
library(xtable) # xtable()

# data --------------------------------------------------------------------
data <- read.csv(file = '../data/analysis/analysis.csv')

# prepare an analysis dataset with each row being a county-year-office
data_long <- data %>% filter(state %in% c("NV", "UT", "MT", "VT", "CO", "NJ", "WA", "HI", "CA")) %>% # restrict analysis to states for which we have 2020 data
  dplyr::select(state, county, county_id, year, state_year_id, dem_share_gov, dem_share_pres, dem_share_sen, treat) %>% 
  mutate(year = as.character(year)) %>% 
  tidyr::pivot_longer(cols = starts_with("dem_share"), names_to = "office", values_to = "dem_share") %>% 
  mutate(county_id = as.factor(county_id), year = as.numeric(year))

# make col 1
m1 <- felm(dem_share ~ treat | county_id + state_year_id | 0 | county_id, data = data_long) # no county trends
b1 <- round(m1$coefficients[1], 3) # beta
se1 <- round(m1$cse[1], 3) # standard error
n1 <- m1$N # number of observations
nc1 <- length(levels(m1$fe$county_id)) # number of counties
ne1 <- length(levels(m1$fe$state_year_id)) # number of elections

# make col 2
m2 <- felm(dem_share ~ treat | county_id + state_year_id + county_id:year| 0 | county_id, data = data_long) # linear county trends. this takes a minute because of county_id:year interaction
b2 <- round(m2$coefficients[1], 3)
se2 <- round(m2$cse[1], 3)
n2 <- m2$N
nc2 <- length(levels(m2$fe$county_id))
ne2 <- length(levels(m2$fe$state_year_id))

# build table
tbl <- tibble(" " = c("VBM", "", "# Counties", "# Elections","# Obs", "County FE", "State by Year FE", "County Trends"),
              "(1)" = c(b1, paste0("(", se1, ")"), nc1, ne1, n1, "Yes", "Yes", "No"),
              "(2)" = c(b2, paste0("(", se2, ")"), nc2, ne2, n2, "Yes", "Yes", "Linear"))
x <- xtable(tbl, caption = "\\textbf{Vote-by-Mail Expansion May Favor Democratic Candidates.}", label = "tab:voteshare_effects")
align(x) <- c("l", "l", rep("c", 2))
print(x, file = "../exhibits/voteshare_table.tex", compress = F, hline.after = c(-1, -1, 0, 5), hline.before = 1,
      include.rownames = F, include.colnames = F, caption.placement = "top",
      add.to.row = list(pos = list(0, 0, nrow(tbl)), command = c("& \\multicolumn{2}{c}{\\hspace{-3em}Dem Vote Share [0-1]} \\\\\n",
                                                                 "& (1) & (2) \\\\\n",
                                                                 "\\hline\\hline\\multicolumn{3}{l}{\\footnotesize{Robust standard errors clustered by county in parentheses.}} \\\\\n")))
